<template>
    <div class="equipment-container">
        <!-- 背景装饰 -->
        <div class="medical-bg"></div>

        <!-- 头部 -->
        <header class="app-header">
             <button class="back-button" @click="goBack" title="返回">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="header-content">
                 <h1>设备管理</h1> <!-- Changed Title -->
            </div>
            <div class="header-placeholder"></div>
        </header>

        <!-- 主要内容区域 -->
        <main class="equipment-content">
            <!-- 设备列表 -->
            <div v-if="equipmentList.length === 0" class="no-data-message">
                暂无设备，请先绑定。
            </div>
            <div v-else v-for="(device, index) in equipmentList" :key="device.id || index" class="equipment-item card-style">
                <div class="equipment-info">
                    <span class="equipment-icon">{{ device.icon || '📱' }}</span>
                    <div class="equipment-details">
                        <span class="equipment-name">{{ device.name || '设备名称' }}</span>
                        <span class="equipment-id">ID: {{ device.id || '未知ID' }}</span>
                        <span :class="['equipment-status', device.status]">状态: {{ getStatusText(device.status) }}</span>
                    </div>
                </div>
                <button class="delete-btn" @click="unbindDevice(index)" title="解绑">
                    <i class="fas fa-unlink"></i> <!-- Changed Icon -->
                </button>
            </div>

             <!-- 绑定按钮 -->
            <div class="bind-button-wrapper">
                <button class="bind-btn primary-button" @click="showDialog = true">
                    <i class="fas fa-plus"></i> 绑定新设备
                </button>
            </div>
        </main>

        <!-- 输入弹窗 -->
        <div v-if="showDialog" class="dialog-overlay">
            <div class="dialog-content card-style">
                <h3>绑定新设备</h3>
                <div class="dialog-form-group">
                     <input v-model="newDevice.id" placeholder="请输入设备ID" />
                </div>
                 <!-- Can add more fields like device name/type if needed -->
                <div class="dialog-buttons">
                    <button class="dialog-btn cancel" @click="showDialog = false">取消</button>
                    <button class="dialog-btn confirm primary-button" @click="bindDevice">确认绑定</button>
                </div>
            </div>
        </div>

        <!-- 底部导航 -->
        <navigation :active-tab="activeTab" @tab-change="handleTabChange" />
    </div>
</template>

<script>
import { reactive, ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import Navigation from '@/components/Navigation.vue';
import axios from 'axios'; // If needed for API calls
import { getItem } from '@/components/Session.vue';
import websocketService from '@/services/websocket';

export default {
    components: { 
        Navigation
    },
    setup() {
        const router = useRouter(); 
        const activeTab = ref('mine'); // Keep 'mine' active as this is accessed from Personal page
        const equipmentList = ref([]); // State for equipment list
        const showDialog = ref(false);
        const newDevice = reactive({ id: '' }); // State for the new device form

        // --- Mock Data & Fetching --- 
        const fetchEquipment = async () => {
            console.log('获取设备列表...');
            try {
                const user = getItem('user');
                const response = await axios.get('/api/device/get', { params: { username: user.username } });
                if (response.data.code === 200) {
                    equipmentList.value = response.data.data.map(device => ({
                        id: device.deviceId,
                        name: device.name,
                        status: 'offline',
                        icon: '📱'
                    }));
                } else {
                    console.error('获取设备列表失败:', response.data.message);
                    equipmentList.value = [];
                }
            } catch (error) {
                console.error('获取设备列表出错:', error);
                equipmentList.value = [];
            }
        };

        const getStatusText = (status) => {
            if (status === 'online') return '在线';
            if (status === 'offline') return '离线';
            return '未知';
        };

        // --- Actions --- 

        const unbindDevice = (index) => {
            const deviceToUnbind = equipmentList.value[index];
            if (!deviceToUnbind) return;

            if (confirm(`确定要解绑设备 "${deviceToUnbind.name || deviceToUnbind.id}" 吗？`)) {
                 console.log(`尝试解绑设备: ${deviceToUnbind.id}`);
                 // TODO: Implement actual API call to unbind
                 // axios.post('/api/equipment/unbind', { deviceId: deviceToUnbind.id, username: '123' })
                 //   .then(res => { ... handle success/error ... fetchEquipment(); // Refresh list })
                 //   .catch(err => { ... });
                 
                 // --- Mock Unbind --- 
                 equipmentList.value.splice(index, 1);
                 alert('设备已解绑 (模拟)');
                 // --- End Mock --- 
            }
        };


        const bindDevice = () => {
            if (!newDevice.id) {
                alert('请输入设备ID！');
                return;
            }
            console.log(`尝试绑定设备: ${newDevice.id}`);
            
            // 获取当前用户信息
            const user = getItem('user');
            if (!user || !user.username) {
                alert('用户信息获取失败，请重新登录');
                return;
            }
            
            // 向后端发起POST请求
            axios.post('/api/device/add', {
                deviceId: newDevice.id,
                username: user.username
            })
            .then(response => {
                if (response.data.code === 200) {
                    // 绑定成功
                    newDevice.id = '';
                    showDialog.value = false;
                    alert('设备绑定成功');
                    // 重新获取设备列表
                    fetchEquipment();
                } else {
                    // 绑定失败
                    alert(`设备绑定失败: ${response.data.message || '未知错误'}`);
                }
            })
            .catch(error => {
                console.error('绑定设备出错:', error);
                alert('绑定设备失败，请稍后重试');
            });
        };

        // --- Navigation --- 
        const handleTabChange = (newTab) => {
            activeTab.value = newTab;
            if (newTab === 'home') {
                router.push('/');
            } else if (newTab === 'mine') {
                router.push('/personal'); // Navigate back to personal page
            }
        };

        const goBack = () => {
             if (window.history.length > 1) {
                 router.go(-1); // Go back to previous page (likely Personal)
             } else {
                 router.push('/personal'); // Fallback to Personal page
             }
        };
        
        // 处理设备状态更新的函数
        const handleDeviceStatusUpdate = (data) => {
            const messages = data.split(';');
            messages.forEach(message => {
                if (message) {
                    const [deviceName, status] = message.split(',');
                    const index = equipmentList.value.findIndex(device => device.name === deviceName);
                    if (index !== -1) {
                        equipmentList.value[index].status = status === '1' ? 'online' : 'offline';
                    }
                }
            });
        };

        // --- Lifecycle --- 
        onMounted(() => {
            fetchEquipment();
            const user = getItem('user');
            // 使用全局 WebSocket 服务
            websocketService.connect('device/status', user.username);
            websocketService.addMessageHandler('device/status', handleDeviceStatusUpdate);
        });

        // 组件卸载时清理
        onUnmounted(() => {
            websocketService.removeMessageHandler('device/status', handleDeviceStatusUpdate);
        });

        return {
            equipmentList,
            showDialog,
            newDevice,
            unbindDevice,
            bindDevice,
            activeTab,
            handleTabChange,
            getStatusText,
            goBack
        };
    }
}
</script>

<style scoped>
/* Reuse styles from Family.vue and adapt names */
.equipment-container {
    min-height: 100vh;
    max-width: 100vw;
    width: 100%;
    background-color: #f8f9fa;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow-x: hidden;
    padding-bottom: 20vw; /* Space for nav bar */
}

/* Background decoration - Remove this empty rule */
/* .medical-bg {
    /* ... * /
} */

/* Header styles - Copy from Family.vue */
.app-header {
    background: linear-gradient(135deg, #4CAF50, #2196F3);
    color: white;
    padding: 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;
}
.back-button { background: none; border: none; color: white; font-size: 5vw; cursor: pointer; padding: 2vw; margin-left: -2vw; line-height: 1; }
.back-button:hover { opacity: 0.8; }
.header-content { text-align: center; flex-grow: 1; }
.header-content h1 { color: white; font-size: 4.5vw; font-weight: 600; margin: 0; }
.header-placeholder { width: 10vw; visibility: hidden; }

/* Content area styles */
.equipment-content {
    flex: 1;
    padding: 4vw;
    overflow-y: auto;
    z-index: 1;
}

.no-data-message {
    text-align: center;
    color: #666;
    padding: 10vw 4vw;
    font-size: 3.8vw;
}

.card-style {
    background: white;
    border-radius: 3vw;
    box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
}

.equipment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4vw;
    margin-bottom: 3vw;
    transition: transform 0.2s;
}

.equipment-item:hover {
    transform: translateY(-0.5vw);
}

.equipment-info {
    display: flex;
    align-items: center;
    gap: 3vw;
}

.equipment-icon {
    font-size: 6vw;
    width: 10vw;
    height: 10vw;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e0f2f7;
    border-radius: 50%;
}

.equipment-details {
    display: flex;
    flex-direction: column;
}

.equipment-name {
    font-weight: 600;
    color: #333;
    font-size: 4vw;
    margin-bottom: 0.5vw;
}

.equipment-id {
    color: #777;
    font-size: 3vw;
    margin-bottom: 0.5vw;
}

.equipment-status {
    font-size: 3vw;
    font-weight: 500;
}

.equipment-status.online {
    color: #4CAF50; /* Green for online */
}

.equipment-status.offline {
    color: #f44336; /* Red for offline */
}

.delete-btn {
    color: #f44336;
    background: none;
    border: none;
    padding: 2vw;
    cursor: pointer;
    font-size: 5vw;
    line-height: 1;
    transition: transform 0.2s;
}

.delete-btn:hover {
    transform: scale(1.1);
}

/* Button styles - Copy from Family.vue */
.bind-button-wrapper { padding: 4vw 0; }
.primary-button {
    width: 100%;
    padding: 4vw;
    background: linear-gradient(135deg, #4CAF50, #2196F3);
    color: white;
    border: none;
    border-radius: 4vw;
    font-size: 4vw;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2vw;
    box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.1);
}
.primary-button:hover { transform: translateY(-0.5vw); box-shadow: 0 0.8vw 2.5vw rgba(0, 0, 0, 0.15); }
.primary-button:active { transform: translateY(0); box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.1); }

/* Dialog styles - Copy from Family.vue */
.dialog-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog-content { 
    background: white; 
    border-radius: 3vw; 
    padding: 4vw; 
    width: 80%; 
    max-width: 500px; 
    box-sizing: border-box;
}
.dialog-content h3 { 
    font-size: 4.5vw; 
    margin: 0 0 4vw 0; 
    color: #333; 
    text-align: center; 
}
.dialog-form-group { 
    margin-bottom: 4vw; 
}
.dialog-form-group input { 
    width: 100%; 
    padding: 3vw; 
    border: 1px solid #ddd; 
    border-radius: 2vw; 
    font-size: 3.5vw; 
    box-sizing: border-box;
}
.dialog-buttons { 
    display: flex; 
    justify-content: space-between; 
    margin-top: 4vw; 
    gap: 3vw;
}
.dialog-btn { 
    flex: 1;
    padding: 3vw 6vw; 
    border-radius: 4vw; 
    font-size: 3.5vw; 
    font-weight: 600; 
    cursor: pointer; 
    transition: all 0.3s; 
    text-align: center;
}
.dialog-btn.cancel { background: #f0f0f0; color: #666; border: none; }
.dialog-btn.confirm { background: #2196F3; color: white; border: none; }
.dialog-btn.cancel:hover { background: #e0e0e0; }
.dialog-btn.confirm:hover { background: #1976D2; }

/* Responsive adjustments - Copy and adapt from Family.vue if needed */
@media screen and (max-width: 320px) {
    /* ... */
}
</style>
